package com.sky.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.user.AddressBookMapper;
import com.sky.mapper.user.ShoppingCartMapper;
import com.sky.mapper.user.UserOrderDetailMapper;
import com.sky.mapper.user.UserOrderMapper;
import com.sky.pojo.AddressBook;
import com.sky.pojo.OrderDetail;
import com.sky.pojo.Orders;
import com.sky.pojo.ShoppingCart;
import com.sky.result.PageResult;
import com.sky.service.user.UserOrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import jdk.net.SocketFlow;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class UserOrderServiceImpl implements UserOrderService {
    @Autowired
    private UserOrderMapper userOrderMapper;
    @Autowired
    private UserOrderDetailMapper userOrderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //异常情况的处理（收货地址为空、超出配送范围、购物车为空）

        //查询地址信息
        AddressBook addressBook = addressBookMapper.findById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new BaseException("未找到收获地址");
        }
        //查询用户购物车数据s
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(BaseContext.getCurrentId());
        if (CollectionUtils.isEmpty(shoppingCarts)) {
            throw new BaseException("购物车没有菜品");
        }
        //本质：写两张表，一张订单表，一张详情表
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //补充缺失数据
        orders.setNumber(UUID.randomUUID().toString().replace("-", ""));//订单号可能有业务规则
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());

        orders.setUserName(addressBook.getConsignee());
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        //预计送达时间
        orders.setDeliveryTime(ordersSubmitDTO.getEstimatedDeliveryTime());
        //出餐时间
//        Integer makeTime = shoppingCartMapper.getMakeTimeByUserId(BaseContext.getCurrentId());
//        orders.setMealTime(LocalDateTime.now().plusMinutes(makeTime));

        userOrderMapper.insert(orders);

        //插入订单明细表
        List<OrderDetail> details = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            details.add(orderDetail);
        }
        //向明细表插入n条数据
        userOrderDetailMapper.insertBatch(details);
        //清理购物车中的数据
        shoppingCartMapper.clean(BaseContext.getCurrentId());

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    @Override
    public void success(String orderNum) {
        Orders orders = userOrderMapper.getByOrderNum(orderNum);
        orders.setPayStatus(Orders.PAID);
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setCheckoutTime(LocalDateTime.now());
        userOrderMapper.updatePaySuccess(orders);
    }

    @Override
    public void reminderNewOrder(String orderNo) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 1);
        jsonObject.put("orderId", orderNo);
        jsonObject.put("content", "您有一条新的订单");
        webSocketServer.sendRemindMessage(jsonObject.toJSONString());
    }

    @Override
    public PageResult historyOrders(int pageNum, int pageSize, Integer status) {
        PageHelper.startPage(pageNum, pageSize);
        OrdersPageQueryDTO pageQueryDTO = new OrdersPageQueryDTO();
        pageQueryDTO.setUserId(BaseContext.getCurrentId());
        pageQueryDTO.setStatus(status);
        Page<Orders> page = userOrderMapper.historyOrders(pageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = userOrderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    @Override
    public void reminder(Long orderId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 2);
        jsonObject.put("orderId", orderId);
        jsonObject.put("content", "用户催单了");
        webSocketServer.sendRemindMessage(jsonObject.toJSONString());
    }

    @Override
    public OrderVO orderDetail(Long id) {
        Orders byOrderId = userOrderMapper.getByOrderId(id);
        List<OrderDetail> orderDetailList = userOrderDetailMapper.getByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(byOrderId, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * - 待支付和待接单状态下，用户可直接取消订单
     * - 商家已接单状态下，用户取消订单需电话沟通商家
     * - 派送中状态下，用户取消订单需电话沟通商家
     * - 如果在待接单状态下取消订单，需要给用户退款
     * - 取消订单后需要将订单状态修改为“已取消”
     */
    @Override
    public void cancel(Long id) {
        //查询订单
        Orders orders = userOrderMapper.getByOrderId(id);

        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消

        if (orders.getStatus() > 2) {
            throw new OrderBusinessException("无法直接取消订单，请联系店家");
        }
        Orders order = new Orders();
        order.setId(id);
        //订单待接单————需要商家退款
        if(orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            //调用微信支付退款接口
            weChatPayUtil.refund(orders.getNumber(),orders.getNumber(),orders.getAmount(),orders.getAmount());
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        order.setStatus(Orders.CANCELLED_ORDER);
        order.setCancelReason("用户取消");
        order.setCheckoutTime(LocalDateTime.now());
        userOrderMapper.setStatus(order);
    }

    @Override
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = userOrderDetailMapper.getByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

}
